//
//  GSDKSuspensionView.m
//  GameSDK
//
//  Created by Johnny on 2017/8/1.
//  Copyright © 2017年 Johnny. All rights reserved.
//

#import "GSDKSuspensionView.h"
#import "GSDKCommonMethod.h"
#import "UIButton+GSDKUIButtonExt.h"
#import "UIViewController+Extension.h"
#import "GSDKComplatformBase.h"
#import "GSDKResponseModel.h"
static NSString * kSuspensionStaticNamed = @"ZYSDK_Resourcres.bundle/pic/ass_common_icon_hide";
static NSString * kSuspensionMoveNamed = @"ZYSDK_Resourcres.bundle/pic/ass_common_icon";
static NSString * kSuspensionOpenLeftNamed = @"ZYSDK_Resourcres.bundle/pic/ass_tb_return_left";
static NSString * kSuspensionOpenRightNamed = @"ZYSDK_Resourcres.bundle/pic/ass_tb_return_right";
static NSString * kWindowLeftNamed = @"ZYSDK_Resourcres.bundle/pic/ass_tb_bg_left";
static NSString * kWindowRightNamed = @"ZYSDK_Resourcres.bundle/pic/ass_tb_bg_right";

typedef NS_ENUM (NSUInteger, LocationTag) {
    kLocationTag_top = 1,
    kLocationTag_left,
    kLocationTag_bottom,
    kLocationTag_right
};

@interface GSDKSuspensionView () {
    BOOL showMenu;                          //是否打开悬浮按钮
    LocationTag locationTag;                //定位
    CGFloat w;                              //屏幕宽度
    CGFloat h;                              //屏幕高度
    UIInterfaceOrientation orientation;     //旋转方向
    CGFloat menuW;                          //悬浮窗整体宽度
    NSTimer * timer;                        //缩进定时器
    BOOL isRetract;                         //是否缩进
}
@property (nonatomic,retain) UIButton * suspensionButton;
@property (nonatomic,retain) UIView * windowView;
@property (nonatomic,retain) UIImageView * windowBgIV;
@end

@implementation GSDKSuspensionView
- (void)dealloc {
    DEBUGMSG(@"GSDKSuspensionView dealloc");
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self setupData];
        [self setupUI];
        [self setupWindowView];
        //注册旋转通知
        [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(svDeviceOrientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setupBadge) name:kSetupBadgeNoticationName object:nil];
        
        [self moveImageAtChange:NO];
        [self initTimer];
        
        [self setupBadge];
        
        self.alpha = 0;
        
        [self computeOfLocation:^{
            self.alpha = 1;
            return ;
        }];
    }
    return self;
}

#pragma mark - 初始化数据
- (void)setupData {
    orientation = [[UIApplication sharedApplication] statusBarOrientation];
    showMenu = NO;
    locationTag = kLocationTag_right;
    w = [GSDKCommonMethod getWidth];
    h = [GSDKCommonMethod getHight];
}

#pragma mark - 初始化视图
- (void)setupUI {
    _suspensionButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_suspensionButton setAdjustsImageWhenHighlighted:NO];
    [_suspensionButton addTarget:self action:@selector(clickSuspensionAction) forControlEvents:UIControlEventTouchUpInside];
    _suspensionButton.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    
    [self addSubview:_suspensionButton];
    
    UIPanGestureRecognizer * panGR = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(pan:)];
    [self addGestureRecognizer:panGR];
    
    UILongPressGestureRecognizer * longGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longImgV:)];
    [longGestureRecognizer setMinimumPressDuration:1.0f];
    [self addGestureRecognizer:longGestureRecognizer];
}

- (void)setupWindowView {
    NSArray * arr = GSDKCOMMONMETHOD.menuModel.tool_bar;
    menuW = [arr count] * 55;
    
    if ([arr count] == 1) {
        menuW = 70;
    }
    
    _windowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
    _windowView.backgroundColor = [UIColor clearColor];
    [self addSubview:_windowView];
    _windowBgIV = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, menuW, self.frame.size.height)];
    [_windowView addSubview:_windowBgIV];
    _windowView.hidden = YES;
    
    for (int i = 0; i <= [arr count] - 1; i++) {
        GSDKResToolbarModel * model = arr[i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button setTitle:model.name forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ZYSDK_Resourcres.bundle/pic/new_%@", model.src]] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/bannerButton.png"] forState:UIControlStateNormal];
        [button setBackgroundImage:[UIImage imageNamed:@"ZYSDK_Resourcres.bundle/pic/bannerButton_highlighted.png"] forState:UIControlStateHighlighted];
        NSString *temp = @".";
        NSRange rang = [model.src rangeOfString:temp];
        NSString *str = [model.src stringByReplacingCharactersInRange:rang withString:@"_s."];
        [button setImage:[UIImage imageNamed:[NSString stringWithFormat:@"ZYSDK_Resourcres.bundle/pic/new_%@",str]] forState:UIControlStateHighlighted];
        button.titleLabel.font = [UIFont systemFontOfSize:13];
        [button setTitleColor:[UIColor colorWithRed:0.0/255.0 green:151.0/255.0 blue:210.0/255.0 alpha:1] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        button.frame = CGRectMake(([arr count] == 1 ? 10 : 5) + i * (50 + 15/[arr count]), 7, 50, 50);
        [_windowView addSubview:button];
        [button addTarget:self action:@selector(tapAction:) forControlEvents:UIControlEventTouchUpInside];
        [button centerImageAndTitle:2];
    }
}

#pragma mark 移动悬浮按钮
- (void)moveImageAtChange:(BOOL)isChange {
    [_suspensionButton setImage:[UIImage imageNamed:isChange ? kSuspensionMoveNamed : kSuspensionStaticNamed] forState:UIControlStateNormal];
}

#pragma mark 打开悬浮窗
- (void)showMenuAtShow:(BOOL)isShow
           andDuration:(CGFloat)duration
           andComplete:(void(^)())complete {
    self.userInteractionEnabled = NO;
    [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:NO];
    __block typeof (self) bSelf = self;
    if (isShow) {
        [_suspensionButton hideBadgeOnButtonIndex:0];
        [self shopTimer];
        _windowView.hidden = NO;
        if (locationTag == kLocationTag_left) {
            [_suspensionButton setImage:[UIImage imageNamed:kSuspensionOpenLeftNamed] forState:UIControlStateNormal];
            [_windowBgIV setImage:[[UIImage imageNamed:kWindowLeftNamed] stretchableImageWithLeftCapWidth:10 topCapHeight:0]];
            self.frame = CGRectMake(0, self.frame.origin.y, self.frame.size.width + menuW, self.frame.size.height);
            [UIView animateWithDuration:duration animations:^{
                bSelf.windowView.frame = CGRectMake(bSelf.suspensionButton.frame.origin.x + bSelf.suspensionButton.frame.size.width, 0, menuW, bSelf.suspensionButton.frame.size.height);
            } completion:^(BOOL finished) {
                [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:YES];
                bSelf.userInteractionEnabled = YES;
                complete();
            }];
        } else {
            [_suspensionButton setImage:[UIImage imageNamed:kSuspensionOpenRightNamed] forState:UIControlStateNormal];
            [_windowBgIV setImage:[[UIImage imageNamed:kWindowRightNamed] stretchableImageWithLeftCapWidth:60 topCapHeight:0]];
            self.frame = CGRectMake(w - self.frame.size.width - menuW, self.frame.origin.y, self.frame.size.width + menuW, self.frame.size.height);
            _suspensionButton.frame = CGRectMake(menuW, 0, _suspensionButton.frame.size.width, _suspensionButton.frame.size.height);
            bSelf.windowView.frame = CGRectMake(menuW, 0, 0, bSelf.suspensionButton.frame.size.height);
            [UIView animateWithDuration:duration animations:^{
                bSelf.windowView.frame = CGRectMake(0, 0, menuW, bSelf.suspensionButton.frame.size.height);
            } completion:^(BOOL finished) {
                [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:YES];
                bSelf.userInteractionEnabled = YES;
                complete();
            }];
        }
    } else {
        if (locationTag == kLocationTag_left) {
            [UIView animateWithDuration:duration animations:^{
                [bSelf.windowView setFrame:CGRectMake(bSelf.suspensionButton.frame.size.width, 0, 0, bSelf.suspensionButton.frame.size.height)];
            } completion:^(BOOL finished) {
                [bSelf setFrame:CGRectMake(bSelf.frame.origin.x, bSelf.frame.origin.y, bSelf.suspensionButton.frame.size.width, bSelf.suspensionButton.frame.size.height)];
                [bSelf.suspensionButton setFrame:CGRectMake(0, 0, bSelf.suspensionButton.frame.size.width, bSelf.suspensionButton.frame.size.height)];
                [bSelf.suspensionButton setImage:[UIImage imageNamed:kSuspensionStaticNamed] forState:UIControlStateNormal];
                self.userInteractionEnabled = YES;
                [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:YES];
                [bSelf.windowView setHidden:YES];
                [bSelf initTimer];
                complete();
                [bSelf.suspensionButton showBadgeOnButonRightIndex:0 andOffset:0];
            }];
        } else {
            [UIView animateWithDuration:duration animations:^{
                [bSelf.windowView setFrame:CGRectMake(menuW, 0, 0, bSelf.suspensionButton.frame.size.height)];
            } completion:^(BOOL finished) {
                [bSelf setFrame:CGRectMake(bSelf.frame.origin.x + menuW, bSelf.frame.origin.y, bSelf.suspensionButton.frame.size.width, bSelf.suspensionButton.frame.size.height)];
                [bSelf.suspensionButton setFrame:CGRectMake(0, 0, bSelf.suspensionButton.frame.size.width, bSelf.suspensionButton.frame.size.height)];
                [bSelf.windowView setFrame:CGRectMake(bSelf.suspensionButton.frame.size.width, 0, 0, bSelf.suspensionButton.frame.size.height)];
                [bSelf.windowView setHidden:NO];
                bSelf.userInteractionEnabled = YES;
                [[UIViewController getCurrentRootViewController].view setUserInteractionEnabled:YES];
                [bSelf.suspensionButton setImage:[UIImage imageNamed:kSuspensionStaticNamed] forState:UIControlStateNormal];
                [bSelf.windowView setHidden:YES];
                [bSelf initTimer];
                complete();
                [bSelf.suspensionButton showBadgeOnButonLeftIndex:0 andOffset:0];
            }];
        }
    }
}

#pragma mark 缩进
- (void)initTimer {
    isRetract = NO;
    timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
    [[NSRunLoop currentRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
}

- (void)shopTimer {
    if (timer && !isRetract) { [timer invalidate]; }
}

- (void)timerFired:(NSTimer*)t {
    [timer invalidate];
    timer = nil;
    
    [self retractBanner];
}

- (void)retractBanner {
    if (!showMenu) {
        __block typeof (self) bSelf = self;
        [UIView animateWithDuration:0.25 animations:^{
            if (locationTag == kLocationTag_left) {
                [bSelf setFrame:CGRectMake(bSelf.frame.origin.x - 35, bSelf.frame.origin.y, bSelf.frame.size.width, bSelf.frame.size.height)];
            } else if (locationTag == kLocationTag_right) {
                [bSelf setFrame:CGRectMake(bSelf.frame.origin.x + 35, bSelf.frame.origin.y, bSelf.frame.size.width, bSelf.frame.size.height)];
            }
        } completion:^(BOOL finished) { isRetract = YES; }];
    }
}

#pragma mark - 定位
- (void)computeOfLocation:(void(^)())complete {
    float x = self.frame.origin.x;
    float y = self.frame.origin.y;
    CGPoint m = CGPointZero;
    m.x = x;
    m.y = y;
    float sW = self.frame.size.width;
    if (iPhoneX) {
        DEBUGMSG(@"orientation = %d", orientation);
        if (orientation == 3) {
            locationTag = kLocationTag_right;
        }
        if (orientation == 4) {
            locationTag = kLocationTag_left;
        }
    } else {
        if (x + 30 < w/2) { locationTag = kLocationTag_left;}
        else { locationTag = kLocationTag_right;}
    }
    
    switch (locationTag) {
        case kLocationTag_top:
            m.y = 0 + self.frame.size.width/2 + 20;
            break;
        case kLocationTag_left:
            m.x = 0;
            if (m.y > h)  m.y = h - sW;
            break;
        case kLocationTag_bottom:
            m.y = h - self.frame.size.height/2;
            break;
        case kLocationTag_right:
            m.x = w - sW;
            if (m.y > h) m.y = h - sW;
            break;
    }
    //这个是在旋转是微调浮标出界时
    if (m.x + sW > w)
        m.x = w - sW;
    if (m.y + sW > h)
        m.y = h - sW;
    __block typeof (self) bSelf = self;
    [UIView animateWithDuration:0.08 animations:^{
        //如果缩进的话，kLocationTag_right的x要加35，kLocationTag_left的要减35
        if (isRetract == YES) {
            if (locationTag == kLocationTag_right) {
                [bSelf setFrame:CGRectMake(m.x + 35, m.y, sW, sW)];
            } else {
                [bSelf setFrame:CGRectMake(m.x - 35, m.y, sW, sW)];
            }
        } else {
            [bSelf setFrame:CGRectMake(m.x, m.y, sW, sW)];
        }
    } completion:^(BOOL finished) {
        complete();
    }];
}

#pragma mark - Action
- (void)clickSuspensionAction {
    if (showMenu) [self showMenuAtShow:NO andDuration:0.01 andComplete:^{ }];
    else [self showMenuAtShow:YES andDuration:0.01 andComplete:^{ }];
    showMenu = !showMenu;
}

- (void)tapAction:(UIButton*)button {
    if (_bannerMenuViewBlock) {
        _bannerMenuViewBlock(button.tag);
    }
}

#pragma mark - UIGestureRecognizer
#pragma mark Pan
- (void)pan:(UIPanGestureRecognizer *)panGestureRecognizer {
    if (showMenu) return;
    
    [self moveImageAtChange:YES];
    UIView * panView = panGestureRecognizer.view;
    float pW = panView.frame.size.width;
    __block typeof (self) bSelf = self;
    [UIView animateWithDuration:0.001 animations:^{
        if (panGestureRecognizer.state == UIGestureRecognizerStateBegan) {
            [bSelf shopTimer];
        }
        if (panGestureRecognizer.state == UIGestureRecognizerStateBegan || panGestureRecognizer.state == UIGestureRecognizerStateChanged) {
            CGPoint translation = [panGestureRecognizer translationInView:panView];
            [panView setCenter:(CGPoint){panView.center.x + translation.x, panView.center.y + translation.y}];
            [panGestureRecognizer setTranslation:CGPointZero inView:panView];
        }
    }];
    [UIView animateWithDuration:0.15 animations:^{
        if (panGestureRecognizer.state == UIGestureRecognizerStateEnded) {
            if (panView.frame.origin.x + 30 <= w/2) {
                if (panView.frame.origin.y <= 0) {
                    [panView setFrame:CGRectMake(0, 0, pW, pW)];
                } else if (panView.frame.origin.y + pW >= h) {
                    [panView setFrame:CGRectMake(0, h - pW, pW, pW)];
                } else {
                    [panView setFrame:CGRectMake(0, panView.frame.origin.y, pW, pW)];
                }
                locationTag = kLocationTag_left;
            } else {
                if (panView.frame.origin.y <= 0) {
                    [panView setFrame:CGRectMake(w - pW, 0, pW, pW)];
                } else if (panView.frame.origin.y + pW >= h) {
                    [panView setFrame:CGRectMake(w - pW, h - pW, pW, pW)];
                } else {
                    [panView setFrame:CGRectMake(w - pW, panView.frame.origin.y, pW, pW)];
                }
                locationTag = kLocationTag_right;
            }
            if (iPhoneX) {
                if (orientation == 3) {
                    locationTag = kLocationTag_right;
                    [panView setFrame:CGRectMake(w - pW, panView.frame.origin.y, pW, pW)];
                }
                if (orientation == 4) {
                    locationTag = kLocationTag_left;
                    [panView setFrame:CGRectMake(0, panView.frame.origin.y, pW, pW)];
                }
            }
            [bSelf initTimer];
            [bSelf moveImageAtChange:NO];
            
            if (locationTag == kLocationTag_right) {
                [_suspensionButton showBadgeOnButonLeftIndex:0 andOffset:0];
            } else {
                [_suspensionButton showBadgeOnButonRightIndex:0 andOffset:0];
            }
        }
    }];
}

#pragma mark - NSNotification
- (void)svDeviceOrientationDidChange:(NSNotification *)notification {
    UIInterfaceOrientation deviceOrientation = [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == deviceOrientation || deviceOrientation == 0 || deviceOrientation == 2) {
        return;
    }
    orientation = deviceOrientation;
    DEBUGMSG(@"orientation = %d", orientation);
    w = [GSDKCommonMethod getWidth];
    h = [GSDKCommonMethod getHight];
    void(^func)(BOOL b) = ^(BOOL b) {
        w = [GSDKCommonMethod getWidth];
        h = [GSDKCommonMethod getHight];
        [self computeOfLocation:^{
            if (b) {
                showMenu = YES;
                [self showMenuAtShow:showMenu andDuration:0 andComplete:^{
                    return ;
                }];
            }
        }];
    };
    BOOL bS = showMenu;
    if (bS) {
        showMenu = NO;
        [self showMenuAtShow:showMenu andDuration:0 andComplete:^{
            func(bS);
        }];
    } else {
        [self shopTimer];
        isRetract = YES;
        func(bS);
    }
}

#pragma mark - Long
- (void)longImgV:(UILongPressGestureRecognizer *)longGR {
    if (longGR.state == UIGestureRecognizerStateBegan) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:[NSString localizedStringForKey:@"GSDK_floathide_prompt" value:@"是否隐藏?"] message:[NSString localizedStringForKey:@"GSDK_floathide_msg" value:@"下次登录时将重新显示"] delegate:self cancelButtonTitle:[NSString localizedStringForKey:@"GSDK_cancel_text" value:@"取消"] otherButtonTitles:[NSString localizedStringForKey:@"GSDK_confirm_text" value:@"确定"], nil];
        [alertView setTag:10001];
        [alertView show];
    }
}

- (void)setupBadge {
    UIButton * button = [self viewWithTag:1];
    [button showBadgeOnButonRightIndex:0 andOffset:-1.5];
    
    if (!showMenu) {
        if (locationTag == kLocationTag_left) {
            [_suspensionButton showBadgeOnButonRightIndex:0 andOffset:0];
        } else if (locationTag == kLocationTag_right){
            [_suspensionButton showBadgeOnButonLeftIndex:0 andOffset:0];
        }
    } else {
        [_suspensionButton hideBadgeOnButtonIndex:0];
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 10001 && buttonIndex == 1) { [GSDKCOMPLATFORM hideSuspensionToolBar]; }
}

@end
